<template>
  <h2>天狗商城购物车</h2>
  <table class="cartTable">
    <tr>
      <th>序号</th>
      <th>名称</th>
      <th>单价</th>
      <th>数量</th>
      <th>小计</th>
      <th>操作</th>
    </tr>
    <tr v-for="(product,index) in products" :key="product.title" :class="{bg:index%2==0}">
      <td>{{index+1}}</td>
      <td>{{product.title}}</td>
      <td>{{formatPrice(product.price,2)}}</td>
      <td>
        <button @click="minus(product,index)">-</button>
        <input v-model="product.quantity" class="quantity" @keyup="product.quantity=(product.quantity>=0?product.quantity:1)"/>
        <button @click="add(product)">+</button>
      </td>
      <td>{{formatPrice(product.quantity*product.price,2)}}</td>
      <td>
        <button @click="remove(index)">删除</button>
      </td>
    </tr>
    <tfoot>
      <td colspan="6">
        {{formatPrice(total,2)}}
      </td>
    </tfoot>
  </table>
</template>

<script lang="ts">
import { computed, reactive } from 'vue';

type Product={
  title: string,
  quantity:number,
  price:number
}

export default {
  setup(){
    //产品数据，响应式对象
    let products=reactive<Product[]>([{
      title: 'paint pot',
      quantity: 9,
      price: 3.95
    }, {
      title: 'polka dots',
      quantity: 17,
      price: 12.3
    }, {
      title: 'pebbles',
      quantity: 5,
      price: 6.71
    }, {
      title: 'Mi Note5',
      quantity: 8,
      price: 2985.6
    }, {
      title: 'iPhone XS',
      quantity: 10,
      price: 8906.72
    }]);

    //计算属性，用于格式化价钱
    const formatPrice=computed(()=>{
      return function(value:number,n:number){
        return "￥"+value.toFixed(n);
      }
    });
    //计算属性，用于计算出总计
    const total=computed(()=>{
      let sum=0;
      products.forEach(p=>{
        sum+=(p.price*p.quantity);
      });
      return sum;
    });

    //移除方法，用于删除购物车中的数据
    const remove=function(index:number){
      if(confirm("确定要删除吗？")){
        //把数组products中从index的位置开始删除1条数据
        products.splice(index,1);
      }
    }

    //减少数量方法
    function minus(product:Product,index:number){
      if(product.quantity>0){
        product.quantity-=1;
      }else{
        remove(index);
      }
    }

    //增加数量方法
    function add(product:Product){
      product.quantity+=1;
    }

    return {products,formatPrice,total,remove,minus,add};
  }
}
</script>

<style>
.cartTable{
  width: 100%;
}
.cartTable,.cartTable td,.cartTable th{
  border-collapse: collapse;
  border:1px solid #999;
}
.cartTable tfoot td{
  text-align: right;
  padding: 10px;
  font-size: 18px;
  font-weight: bold;
  color: red;
}
.quantity{
  width: 40px;
}
.bg{
  background: #def;
}
</style>
